package com.edu.tool.aspect;



import com.edu.tool.service.user.SysLoginTokenService;
import com.edu.tool.util.json.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

/**
 * 
 * @FileName：TokenAspect.java
 * @Description：@TODO
 * @Author：thy
 * @CreateTime：上午10:28:35
 */
@Component
@Aspect
public class TokenAspect {
	private static Logger log = Logger.getLogger(TokenAspect.class);
	
	@Autowired
	private SysLoginTokenService loginTokenService;

	@Pointcut("(execution(public * com.edu.tool.*.controller.*Controller.*(..))) && !@annotation(com.edu.tool.annotation.NotCheckToken)")
	public void pointCut() {
	}

	@Around("pointCut()")
	public Object around(ProceedingJoinPoint pjp) throws Throwable {
		log.info("Check Token begin...");
		Object result = null;
        MethodSignature methodSignature = (MethodSignature)pjp.getSignature();
        Method method = methodSignature .getMethod();
        Type returnType = method.getGenericReturnType();// 返回类型
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		boolean isTimeout = true;
        String token = (String)request.getHeader("Authorization");
        if(!StringUtils.isEmpty(token)){
    		log.info("Token is "+token);
        	Map checkResult = loginTokenService.check(token);
        	if(checkResult!=null&&"ok".equals(checkResult.get("retcode")))
        	{//会话有效
        		isTimeout = false;
        		//request.getSession().setAttribute("tenantId", checkResult.get("tenantId"));
        		//request.getSession().setAttribute("userId", checkResult.get("userId"));
        		//request.getSession().setAttribute("contactId", checkResult.get("contactId"));
        		//request.getSession().setAttribute("accountId", checkResult.get("accountId"));
        	}
        }
        if(isTimeout)
        {//超时
    		log.info("Token is Timeout");
	        if(returnType.equals(Class.forName(ModelAndView.class.getName())))
			{//返回错误页面
				result = new ModelAndView("system/error");
			}
			else
			{
				HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
				Map errorResult = new HashMap();
				errorResult.put("retcode", "timeout");
				errorResult.put("retmsg", "会话超时，请重新登录");
				String responseStr = JsonUtil.toJson(errorResult);
			    response.setCharacterEncoding("UTF-8");  
			    response.setContentType("application/json; charset=utf-8");  
			    PrintWriter out = null;  
			    try {  
			        out = response.getWriter();  
			        out.append(responseStr);
			    } catch (IOException e) {  
			       log.error("IOException", e);
			    } finally {  
			        if (out != null) {
			        	out.close();  
			        }  
			    }
			}
        }
        else
        {
    		log.info("Token is valid");
        	result = pjp.proceed(pjp.getArgs());
        }
        return result;
	}
}

